<template>
    <!--  <div>
          <router-link to="/addUser">新增歌曲</router-link>
      </div> -->
    <div class="handle-box">
      <el-button @click="openDel">批量删除</el-button>
      <el-input v-model="songName" @keyup.enter="getSongs(1)" placeholder="歌名搜索"></el-input>
      <el-button type="primary" @click="addSongVisible = true">添加歌单</el-button>
    </div>
    <el-table :data="tableData.records" stripe border @selection-change="handleSelectionChange" style="width: 100%">
      <!-- <el-table-column prop="id" label="Id(一般不展示)" width="180" /> -->
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column prop="applicationEmployee" label="员工名"  />
      <el-table-column prop="applicationDate" label="离职时间"  />
      <el-table-column prop="startTime" label="申请开始时间" />
      <el-table-column prop="endTime" label="申请结束时间"  />
      <el-table-column label="申请附件" width="110" align="center">
        <!-- v-slot 具名插槽，等于号，用于获取数据 -->
        <template v-slot="scope">
          <!-- <img :src="attachImageUrl(scope.row.pic)" style="width: 80px"/> -->
          <img :src="'data:image/jpeg;base64,' + scope.row.applicationPath" style="width: 80px" />
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="160" align="center">
        <template v-slot="scope">
          <el-button @click="editRow(scope.row)">编辑</el-button>
          <el-button type="danger" @click="openDelRow(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :small="false"
        :page-sizes="[1,10, 20, 30, 40,50]"
        :disabled="false"
        layout="total,sizes, prev, pager, next,jumper"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible">
      <el-form :model="editForm">
        <el-form-item label="歌曲名字">
          <el-input v-model="editForm.songName"></el-input>
        </el-form-item>
        <el-form-item label="歌词">
          <el-input type="textarea" v-model="editForm.geci"></el-input>
        </el-form-item>
        <el-form-item>
          <el-upload ref="upload" v-model:file-list="fileList" list-type="picture" :on-remove="handleRemove"
            :auto-upload='false' :limit="1" :on-exceed="handleExceed" :on-change="handleChange">
            <img v-if="disabled" :src="editForm.imagePath" style="width: 100px;" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <div>
      <!-- 全部删除提示框 -->
      <el-dialog title="提示" v-model="delVisible" width="300px" center>
        <div align="center">删除不可恢复，是否确定删除？</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelDel">取 消</el-button>
            <el-button type="primary" @click="deleteAll">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 删除一行提示框 -->
      <el-dialog title="提示" v-model="delRowVisible" width="300px" center>
        <div align="center">删除不可恢复，是否确定删除？</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelDel">取 消</el-button>
            <el-button type="primary" @click="deleteRow">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog title="新增歌曲" v-model="addSongVisible" width="800px" center>
        <div>
          <upload-img></upload-img>
        </div>
      </el-dialog>
    </div>
  </template>
    
  <script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import emitter from "@/utils/emitter";
  import axiosHttp from '../http/AxiosUtil'
  import uploadImg from '../components/user/uploadImg.vue'
  //当前页码
  const currentPage = ref(1)
  //数据总量
  const dataTotal = ref(100)
  //每页数据量
  const pageSize = ref(1)
  /* -------------分页---------------------- */
  //page-size 改变时触发,val点击的数据size
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getSongs(1);
  }
  //	current-page 改变时触发
  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getSongs(val)
  }
  //搜索关键字
  const songName = ref()
  //打开新增弹窗
  const addSongVisible = ref(false)
  /* 
    需要新增歌曲组件中加入：emitter.emit("cancelAdd", false);这段代码在新增成功后执行
  */
  emitter.on("cancelAdd", (msg) => {
    addSongVisible.value = msg as boolean;
    getSongs(1);
  });
  //表格数据
  const tableData = ref({
    records: []
  })
  onMounted(() => {
    getSongs(1);
  })
  //查询获取歌曲数据
  function getSongs(current:number) {
    axiosHttp.post('/indApplication/getApplication', {
      params: {
        songName: songName.value,
        current: current,
        size: pageSize.value
      }
    }).then(response => {
      let data = response.data
      tableData.value = data;
      dataTotal.value = data.total
    })
  }
  /**
     * 编辑
     */
  const editVisible = ref(false);
  const editForm = reactive({
    id: "",
    songName: "",
    geci: "",
    imagePath: "",
  });
  /* 打开弹窗 */
  function editRow(row: any) {
    editForm.id = row.id;
    editForm.songName = row.songName;
    editForm.geci = row.geci;
    editForm.imagePath = 'data:image/jpeg;base64,' + row.imagePath;
    editVisible.value = true;
    disabled.value = true;//显示已上传图
  }
  //保存更新
  function saveEdit() {
    const token = localStorage.getItem('Token')
    let param: any = new FormData();
    param.append('id', editForm.id);
    param.append('songName', editForm.songName);
    param.append('geci', editForm.geci);
    if (fileList.value.length > 0) {
      param.append('fm', fileList.value[0].raw);
    }
    //在这等价于上方的formData
    // const param = {
    //   id:editForm.id,
    //   songName:editForm.songName,
    //   geci:editForm.geci,    
    //   fm:Object,
    // }
    if (fileList.value.length > 0) {
      param.fm = fileList.value[0].raw;
    }
    axiosHttp.post('/songs/updateMusic', param, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("更新成功！")
          getSongs(currentPage.value);
          cancel()
        }
      })
  }
  function cancel() {
    editVisible.value = false;
    if (fileList.value.length > 0) {
      fileList.value.pop();
    }
  }
  /**
  * 删除
  */
  const idx = ref<String>("-1"); // 记录当前要删除的行
  const multipleSelection: any = ref([]); // 记录当前要删除的列表
  const delVisible = ref(false); // 显示删除框
  const delRowVisible = ref(false); // 显示删除一行框
  
  
  async function confirm() {
  
  }
  function handleSelectionChange(val: any) {
    multipleSelection.value = val;
  }
  
  function deleteRow() {
    let ids = [idx.value];
    deleteRequest(ids);
  }
  //打开删除窗
  function openDelRow(id: String) {
    delRowVisible.value = true
    idx.value = id
  }
  //  打开删除确认窗
  function openDel() {
    delVisible.value = true;
  }
  //关闭删除窗
  function cancelDel() {
    delVisible.value = false;
    delRowVisible.value = false;
  }
  //请求后端的删除接口
  function deleteRequest(ids: any) {
    axiosHttp.post('/songs/delSongs', JSON.stringify(ids), {
      headers: {
        'Content-Type': 'application/json'//后端接口的参数需要加上@RequestBody
      }
    })
      .then(response => {
        if (response.data.code == '1') {
          ElMessage.info("删除成功！")
          cancelDel()
          multipleSelection.value = [];
          getSongs(1);
        } else {
          ElMessage.error("删除失败！")
        }
      })
  }
  //删除请求
  function deleteAll() {
    let ids = [];
    for (let item of multipleSelection.value) {
      ids.push(item.id)
    }
    deleteRequest(ids)
  }
  /* -------------------------图片上传------------------------------ */
  import { type UploadProps, type UploadFile, type UploadFiles, type UploadUserFile, type UploadRawFile, type UploadInstance, ElDialog } from 'element-plus'
  //是否显示已上传图片
  const disabled = ref(true)
  //上传的文件信息
  const fileList = ref<UploadUserFile[]>([])
  //绑定的上传组件
  const upload = ref<UploadInstance>()
  
  //文件预览所需地址
  const imageUrl = ref('')
  //是否弹窗
  const dialogVisible = ref(false)
  //删除时候会触发的方法
  const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    setTimeout(() => {
      disabled.value = true;
    }, 1000); //延时2秒钟执行
    //显示已上传图
  }
  /* 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用 */
  const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log(uploadFile);
    console.log(uploadFiles);
    disabled.value = false;
  }
  //超出上传数量时触发的方法
  const handleExceed: UploadProps['onExceed'] = (files) => {
    //"!" 强制链式调用
    //替换预览图片
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    upload.value!.handleStart(file)
  
    //用来保存图片，用以上传
    fileList.value.splice(0, 1, file)
  }
  /* -------------------------图片上传结束------------------------------ */
  /* data类型Url的形式：
    data:,<文本数据>
  
    data:text/plain,<文本数据>
  
    data:text/html,<HTML代码>
  
    data:text/html;base64,<base64编码的HTML代码>
  
    data:text/css,<CSS代码>
  
    data:text/css;base64,<base64编码的CSS代码>
  
    data:text/javascript,<Javascript代码>
  
    data:text/javascript;base64,<base64编码的Javascript代码>
  
    编码的gif图片数据
  
    编码的png图片数据
  
    编码的jpeg图片数据
  
    编码的icon图片数据
    */
  </script>
    